package com.ruoyi.web.controller.warning;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.warning.domain.http.DSResponse;
import com.ruoyi.warning.service.IndexService;
import com.ruoyi.warning.service.LibreService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import java.util.Map;

import static com.ruoyi.framework.datasource.DynamicDataSourceContextHolder.log;

/**
 * <p>
 * 告警模版表 前端控制器
 * </p>
 *
 * @author chenhc
 * @since 2025-02-20
 */
@RestController
@RequestMapping("/index")
@Api(tags = "首页", description = "用于处理首页相关操作的控制器")
public class IndexController {
    @Resource
    private IndexService indexService;
    @Resource
    private LibreService libreService;


    @ApiOperation("获取所有设备")
    @GetMapping(value = "/getAllDevices")
    public R getAllDevices()
    {
        return R.ok(libreService.getAllDevices());
    }

    @ApiOperation("获取设备的详细信息")
    @GetMapping(value = "/getDeviceDetail/{hostname}")
    public R getDeviceDetail(@PathVariable String hostname) throws Exception
    {
        return R.ok(libreService.getDeviceDetail(hostname));
    }

    @ApiOperation("获取所有服务")
    @GetMapping(value = "/getAllServices")
    public R getAllServices()
    {
        return R.ok(libreService.getAllServices());
    }

    @ApiOperation("获取所有端口")
    @GetMapping(value = "/getAllPorts")
    public R getAllPorts()
    {
        return R.ok(libreService.getAllPorts());
    }

    @Anonymous
    @ApiOperation("获取告警监控情况")
    @GetMapping(value = "/getWarningSituation/{level}")
    public R getWarningSituation(@PathVariable Integer level)
    {
        return R.ok(indexService.getWarningSituation(level));
    }

    @ApiOperation("获取告警滚动条")
    @GetMapping(value = "/getWarningScrollBar")
    public R getWarningScrollBar()
    {
        return R.ok(indexService.getWarningScrollBar());
    }

    @ApiOperation("获取资源总览情况")
    @GetMapping(value = "/getResourcesOverview")
    public R getResourcesOverview()
    {
        return R.ok(indexService.getResourcesOverview());
    }

    @ApiOperation("右侧-获取各参数的使用率")
    @GetMapping(value = "/getDeviceUsage")
    public R getDeviceUsage()
    {
        return R.ok(indexService.getDeviceUsage());
    }

    @ApiOperation("ds服务调用")
    @Anonymous
    @PostMapping(value = "/getDSService")
    public R getDSService(@RequestBody Map<String,String> map) throws JsonProcessingException {
        DSResponse response = libreService.getDSService(map.get("content"));
        System.out.println(response);
        if(ObjectUtils.isEmpty(response.getData())){
            return R.ok("AI服务异常，请稍后再试。");
        }
        String dataResponse = response.getData().getResponse();
        dataResponse = dataResponse.substring(dataResponse.indexOf("</think>")+8);
//        dataResponse = dataResponse.replaceAll("\\n", "");
        return R.ok(dataResponse);
    }

    @ApiOperation("获取统计信息")
    @GetMapping(value = "/getStatistics")
    public R getStatistics() {
        return R.ok(indexService.getStatistics());
    }

    @ApiOperation("获取设备类型的统计信息")
    @GetMapping(value = "/getDeviceStatistics")
    public R getDeviceStatistics() {
        return R.ok(indexService.getDeviceStatistics());
    }

    @ApiOperation("ds服务调用流式")
    @Anonymous
    @PostMapping(value = "/getDSServiceStream",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter getDSServiceStream(@RequestBody Map<String,String> map){

        SseEmitter emitter = new SseEmitter(Long.MAX_VALUE);
        String content = map.get("content");
        content = content.replace("\n"," ");
        System.out.println(content);
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建包含参数的 URL
//            URIBuilder uriBuilder = new URIBuilder(host);
            URIBuilder uriBuilder = new URIBuilder("http://172.30.30.91/indexapi.php");
            // 创建请求对象
            HttpPost request = new HttpPost(uriBuilder.build());
            content="使用专业的语气与我交流： "+content;
            String json = "{\"api_key\": \"haocheng0511\",\"content\": \""+content+"\"}";
            request.setEntity(new StringEntity(json, "UTF-8"));
            String requestParams = EntityUtils.toString(request.getEntity(), "UTF-8");
            System.out.println("请求参数: " + requestParams);
            // 添加请求头
            request.setHeader(HttpHeaders.ACCEPT, "application/json");
            // 设置 Content-Type 请求头，明确编码格式为 UTF-8
            request.setHeader(HttpHeaders.CONTENT_TYPE, "application/json; charset=UTF-8");
            request.setHeader("X-API-Key", "haocheng0511");
            // 执行请求
            try (CloseableHttpResponse response = httpClient.execute(request)) {
                // 检查状态码
                int statusCode = response.getStatusLine().getStatusCode();
                System.out.println("请求方法: " + request.getMethod());
                System.out.println("请求 URL: " + request.getURI());
                System.out.println("请求头信息:");
                for (org.apache.http.Header header : request.getAllHeaders()) {
                    System.out.println(header.getName() + ": " + header.getValue());
                }
                System.out.println("参数: " + request.getEntity());
                System.out.println("HTTP Status Code: " + statusCode);
                // 获取响应实体
                HttpEntity entity = response.getEntity();
                System.out.println("+++++++++++++++++++++");
                emitter.send(EntityUtils.toString(entity, "UTF-8"));
            }
            } catch (Exception e) {
                e.printStackTrace();
                System.err.println("请求失败: " + e.getMessage());
            }

        // 超时处理
        emitter.onTimeout(() -> {
            emitter.complete();
            log.info("Connection timeout");
        });
        return emitter;
    }
}
